package com.chuji.crmcj.act;

import android.app.AlertDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.adapter.NoUserAdapter;
import com.chuji.crmcj.bean.OrderDetailBean;
import com.chuji.crmcj.bean.OrderDetailInfo;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.ConstantValue;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by w.pitt on 2016/1/15.
 */
public class OrderDetialAct extends BaseActivity implements View.OnClickListener {

    private Button mBtOrderDeal;
    private Button mBtApplyDef;
    private RelativeLayout mLlCustomer;
    private TextView mTvWantCar;
    private TextView mTvCommitOrder;
    private TextView mTvOrderDetail;
    private TextView tv_time;
    private TextView mTvCarModels;
    private TextView mTvCarConf;
    private TextView mTvCarColor;
    private TextView mTvFrame;
    private TextView mTvDealMoney;
    private TextView mTvBuyType;
    private TextView mTvDeliverData;
    private TextView mTvPayType;
    private TextView mTvOwnerName;
    private TextView mTvIdCard;
    private AlertDialog orderDialog;
    private EditText mEtDefRemark;
    private AlertDialog dealDialog;
    private String customerID;
    private String defRemark;
    private TextView mName;
    private TextView mNumber;
    private ImageView mIvLevel;
    private LinearLayout mLlDeal;
    private View mLlAppDef;
    private int lable;
    private LinearLayout mLlExCusBtn;
    private TextView mTvCarName;
    private TextView mTvConfName;
    private TextView mTvDealType;
    private TextView mTvColorName;
    private View view;
    private ListView mLvAppDef;
    private int roleType;

    private TextView mTvSureTime;
    private TextView mTvSaleName;
    private TextView mTvClientNum;
    private TextView mTvCarType;
    private TextView mTvClientName;
    private LinearLayout mLlMagOrdDetail;
    private TextView mTvOrderCreat;
    private String defReason;
    private String orderInfoID;
    private String cusName;
    private String tel;
    private String carModel;
    private String userID;
    private TextView mTvKongbai;
    private ImageView mIvOrderLevel;
    private LinearLayout ll_content;
    private ScrollView scroll;

    @Override
    protected void initView() {
        setContentView(R.layout.act_order_detail);
        scroll = (ScrollView) findViewById(R.id.scroll);
        mIvLevel = (ImageView) findViewById(R.id.iv_level);
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        mTvKongbai = (TextView) findViewById(R.id.tv_kongbai);
        mTvOrderCreat = (TextView) findViewById(R.id.tv_order_creat);
        mLlMagOrdDetail = (LinearLayout) findViewById(R.id.ll_mag_order_detail);
        mTvClientName = (TextView) findViewById(R.id.tv_client_name);
        mTvCarType = (TextView) findViewById(R.id.tv_car_type);
        mTvClientNum = (TextView) findViewById(R.id.tv_client_num);
        mTvSaleName = (TextView) findViewById(R.id.tv_salesman_name);
        mTvSureTime = (TextView) findViewById(R.id.tv_handle_time);
        mLlDeal = (LinearLayout) findViewById(R.id.ll_deal);
        mTvCarName = (TextView) findViewById(R.id.tv_car_name);
        mTvConfName = (TextView) findViewById(R.id.tv_conf_name);
        mTvColorName = (TextView) findViewById(R.id.tv_color_name);
        mTvDealType = (TextView) findViewById(R.id.tv_least_time);
        mLlAppDef = findViewById(R.id.ll_application_defeat);
        mLlExCusBtn = (LinearLayout) findViewById(R.id.expect_cus_btn);
        mIvOrderLevel = (ImageView) findViewById(R.id.iv_order_level);
        mLlCustomer = (RelativeLayout) findViewById(R.id.ll_coustomer);
        mTvWantCar = (TextView) findViewById(R.id.tv_want_car);
        mTvOrderDetail = (TextView) findViewById(R.id.tv_order_detail);
        tv_time = (TextView) findViewById(R.id.tv_time);
        mName = (TextView) findViewById(R.id.tv_name);
        mTvCarModels = (TextView) findViewById(R.id.tv_car_models);
        mTvCarConf = (TextView) findViewById(R.id.tv_car_conf);
        mTvCarColor = (TextView) findViewById(R.id.tv_car_color);
        mTvFrame = (TextView) findViewById(R.id.tv_frame);
        mTvDealMoney = (TextView) findViewById(R.id.tv_deal_money);
        mTvBuyType = (TextView) findViewById(R.id.tv_buy_type);
        mTvDeliverData = (TextView) findViewById(R.id.tv_deliver_data);
        mTvPayType = (TextView) findViewById(R.id.tv_pay_type);
        mTvOwnerName = (TextView) findViewById(R.id.tv_owner_name);
        mTvIdCard = (TextView) findViewById(R.id.tv_id_card);
        mNumber = (TextView) findViewById(R.id.tv_number);
    }

    @Override
    protected void initData() {
        roleType = SPUtils.getInt(UIUtils.getContext(), "RoleType", -1);
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");

        Intent intent = getIntent();
        lable = intent.getIntExtra("Lable", -1);
        orderInfoID = intent.getStringExtra("OrderInfoID");
        customerID = intent.getStringExtra("CustomerID");
        cusName = intent.getStringExtra("Name");
        tel = intent.getStringExtra("Tel");
        carModel = intent.getStringExtra("CarModel");

        mName.setText(cusName);
        if (tel.length() == 11) {
            mNumber.setText(NumberUtils.parsePhoneNumber(tel));
        } else {
            mNumber.setText(tel);
        }

        mTvWantCar.setText(carModel);
        mTvDealType.setText("订单车型");

        /*非销售端*/
        if (roleType != 1) {
            mLlCustomer.setVisibility(View.GONE);
            mLlExCusBtn.setVisibility(View.GONE);
            mLlMagOrdDetail.setVisibility(View.VISIBLE);
            reqMagOrdDel();
        } else {
            reqOrderDetail();
        }

        if (lable == ConstantValue.FullPayFragment) {
            mTvOrderDetail.setText("成交详情");
            mTvCarName.setText("成交成型");
            mTvConfName.setText("成交配置");
            mLlExCusBtn.setVisibility(View.GONE);
            mTvDealType.setText("成交车型");
            mTvColorName.setText("成交颜色");
            mTvOrderCreat.setVisibility(View.GONE);
            mIvLevel.setVisibility(View.GONE);
        }
        if (lable == ConstantValue.OrderFragment) {
            mIvOrderLevel.setVisibility(View.VISIBLE);
            mTvKongbai.setVisibility(View.VISIBLE);
        }
        mTvBarTitle.setText("订单详情");
    }

    private void reqMagOrdDel() {
        String strURL = String.format(UrlUtils.OrderDetailPeter + "&UserID=%s&OrderInfoID=%s", userID, orderInfoID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final OrderDetailBean ordDelInfo = JSON.parseObject(s, OrderDetailBean.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ordDelInfo.getCount() != 0) {
                            scroll.setVisibility(View.VISIBLE);
                            if (ordDelInfo.getApiParamObj().get(0).getOrderBargainType() == 0) {
                                //跟进状态
                                mIvLevel.setImageDrawable(CommonUtil.getLevelIcon("O"));
                                mIvLevel.setVisibility(View.VISIBLE);
                                mTvKongbai.setVisibility(View.VISIBLE);
                            } else {
                                //已确认状态
                                mIvLevel.setVisibility(View.GONE);
                                mTvKongbai.setVisibility(View.GONE);
                            }

                            mTvClientName.setText(ordDelInfo.getApiParamObj().get(0).getCustomerName());
                            mTvCarType.setText(ordDelInfo.getApiParamObj().get(0).getCarModel());
                            mTvClientNum.setText(ordDelInfo.getApiParamObj().get(0).getCustormerTel());
                            mTvSaleName.setText(ordDelInfo.getApiParamObj().get(0).getSaleName());
                            mTvSureTime.setText(ordDelInfo.getApiParamObj().get(0).getOrderConfirmTime());

                            tv_time.setText(ordDelInfo.getApiParamObj().get(0).getOrderTime());
                            mTvCarModels.setText(ordDelInfo.getApiParamObj().get(0).getCarModel());
                            mTvCarConf.setText(ordDelInfo.getApiParamObj().get(0).getCarConfiguration());
                            mTvCarColor.setText(ordDelInfo.getApiParamObj().get(0).getCarColor());
                            mTvFrame.setText(ordDelInfo.getApiParamObj().get(0).getVIN());
                            mTvDeliverData.setText(ordDelInfo.getApiParamObj().get(0).getDeliveryTime());
                            mTvBuyType.setText(ordDelInfo.getApiParamObj().get(0).getBargainType());
                            mTvDealMoney.setText(ordDelInfo.getApiParamObj().get(0).getAmount());
                            mTvPayType.setText(ordDelInfo.getApiParamObj().get(0).getPaymentType());
                            mTvOwnerName.setText(ordDelInfo.getApiParamObj().get(0).getUserName());
                            mTvIdCard.setText(ordDelInfo.getApiParamObj().get(0).getCard());
                        } else {
                            scroll.setVisibility(View.GONE);
                            UIUtils.showToastSafe("无数据");
                        }
                    }
                });
            }
        });
    }

    private void reqOrderDetail() {
        String strURL = String.format(UrlUtils.GETORDERDETAILINFO + "&CustomerID=%s", customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final OrderDetailInfo orderDetailInfo = JSON.parseObject(s, OrderDetailInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (orderDetailInfo.getApiParamObj().size() != 0) {
                            scroll.setVisibility(View.VISIBLE);
                            tv_time.setText(orderDetailInfo.getApiParamObj().get(0).getCreateTime());
//                        mNumber.setText(orderDetailInfo.getApiParamObj().get(0).);
                            mTvCarModels.setText(orderDetailInfo.getApiParamObj().get(0).getCarModel());
                            mTvCarConf.setText(orderDetailInfo.getApiParamObj().get(0).getCarConfiguration());
                            mTvCarColor.setText(orderDetailInfo.getApiParamObj().get(0).getCarColor());
                            mTvFrame.setText(orderDetailInfo.getApiParamObj().get(0).getVIN());
                            mTvDeliverData.setText(orderDetailInfo.getApiParamObj().get(0).getDeliveryTime());
                            mTvBuyType.setText(orderDetailInfo.getApiParamObj().get(0).getBargainType());
                            mTvDealMoney.setText(orderDetailInfo.getApiParamObj().get(0).getAmount());
                            mTvPayType.setText(orderDetailInfo.getApiParamObj().get(0).getPaymentType());
                            mTvOwnerName.setText(orderDetailInfo.getApiParamObj().get(0).getUserName());
                            mTvIdCard.setText(orderDetailInfo.getApiParamObj().get(0).getCard());
                        } else {
                            UIUtils.showToastSafe("无数据");
                            scroll.setVisibility(View.GONE);
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void initListener() {
        mLlDeal.setOnClickListener(this);
        mLlAppDef.setOnClickListener(this);
        mBtnBarLeftArr.setOnClickListener(this);
        mLlCustomer.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_deal:
                OrderDealDialog();
                break;
            case R.id.ll_application_defeat:
                AppDefeatDialog();
                break;
            case R.id.btn_left_arr:
                finish();
                break;
            case R.id.ll_coustomer:
                Intent intent = new Intent(this, ClientDetailAct.class);
                startActivity(intent);
                break;
        }
    }

    private String seletReason;

    private void AppDefeatDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        orderDialog = builder.create();
        view = View.inflate(this, R.layout.layout_apply_def, null);
        // dialog.setView(view);
        mEtDefRemark = (EditText) view.findViewById(R.id.et_def_remark);
        mLvAppDef = (ListView) view.findViewById(R.id.lv_def_reason);

        NoUserAdapter adapter = new NoUserAdapter(1);
        mLvAppDef.setAdapter(adapter);
//        NiceSpinner defReason = (NiceSpinner) view.findViewById(R.id.def_reason);
//        final ArrayList<String> dataset = new ArrayList<String>(Arrays.asList("放弃购车", "选购竞品", "同城购车"));
//        defReason.attachDataSource(dataset);
//        defReason.setSelectedIndex(0);
//        defReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                seletReason = dataset.get(i);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//            }
//        });
        orderDialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                defReason = SPUtils.getString(UIUtils.getContext(), "defReason", "");
                defRemark = mEtDefRemark.getText().toString().trim();
                if (TextUtils.isEmpty(defReason)) {
                    UIUtils.showToastSafe("请选择战败原因");
                } else if (TextUtils.isEmpty(defRemark)) {
                    UIUtils.showToastSafe("请填写备注信息");
                } else {
                    appOrderDef();
                    orderDialog.dismiss();
                }
            }
        });

        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orderDialog.dismiss();
            }
        });
        orderDialog.show();
    }

    private void appOrderDef() {
//        String strURL = String.format(UrlUtils.DEFAPPFORORDER +
//                "&CustomerID=%s&SalesID=%s&DefeatReason=%s&Comment=%s&OrderInfoID=%s", customerID, salerId, seletReason, defRemark, "123");
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("战败申请成功！");
//                        orderDialog.dismiss();
//                        finish();
//                    }
//                });
//            }
//        });
        String strURL = String.format(UrlUtils.DEFAPPFORORDER);
        Map<String, String> map = new HashMap<String, String>();
        map.put("CustomerID", customerID);
        map.put("SalesID", userID);
        map.put("DefeatReason", seletReason);
        map.put("Comment", defRemark);
        map.put("OrderInfoID", orderInfoID);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("战败申请已提交");
            }
        });
    }

    private void OrderDealDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        dealDialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_order_deal, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dealDialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqOrderDeal();
                dealDialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dealDialog.dismiss();
            }
        });
        dealDialog.show();
    }

    private void reqOrderDeal() {
//        String strURL = String.format(UrlUtils.SUREORDERDEAL +
//                "&SalesID=%s&CustomerID=%s&FlowID=%s", salerId, customerID, flowID);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("订单确认成功！");
//                        //Todo 后期需要加   加载动画。
//                        finish();
//                    }
//                });
//            }
//        });

        String strURL = String.format(UrlUtils.SUREORDERDEAL);
        Map<String, String> map = new HashMap<String, String>();
        map.put("SalesID", userID);
        map.put("CustomerID", customerID);

        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("订单确认成功！");
            }
        });
    }
}
